//
//  ALtimeterManager.m
//  demo1
//
//  Created by A on 2023/3/6.
//

#import "ALtimeterManager.h"
#import <CoreMotion/CoreMotion.h>

@interface ALtimeterManager()
@property (nonatomic,strong) CMAltimeter* altimeter;
@property (nonatomic,strong) AltimeterResult altimeterCallback;
@end

@implementation ALtimeterManager

+ (ALtimeterManager *)sharedManager{
  static ALtimeterManager * _sharedManager = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    _sharedManager = [[ALtimeterManager alloc] init];
  });
  return _sharedManager;
}

- (CMAltimeter *)altimeter{
  if(!_altimeter){
    _altimeter = [[CMAltimeter alloc] init];
  }
  return _altimeter;
}

- (void)startMonitorWithCallback:(AltimeterResult)callback{
  self.altimeterCallback = callback;
  if(![CMAltimeter isRelativeAltitudeAvailable]){
    callback(@{@"resultCode":@(-1)});
    return;
  }
  //开始检测
  [self.altimeter startRelativeAltitudeUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAltitudeData * _Nullable altitudeData, NSError * _Nullable error) {
    if(self.altimeterCallback){
      self.altimeterCallback(@{
        @"resultCode":@(0),
        @"pressure":altitudeData.pressure
      });
      self.altimeterCallback = nil;
    }
    
  }];
}

- (void)stopMonitor{
  [self.altimeter stopRelativeAltitudeUpdates];
}

@end
